package com.coolingme.promotion;

import com.coolingme.promotion.strategy.CashbackStrategy;
import com.coolingme.promotion.strategy.CouponStrategy;
import com.coolingme.promotion.strategy.DefaultStrategy;
import com.coolingme.promotion.strategy.GroupBuyStrategy;

import java.util.HashMap;
import java.util.Map;

/**
 * 使用工厂模式和单例模式获取策略，减少if else/switch
 *
 * @author wangyue
 * @date 2020-09-22 21:52
 */
public class PromotionStrategyFactory {

    /**
     * 策略的容器
     */
    private static Map<String, IPromotionStrategy> strategyMap = new HashMap<>();

    /**
     * 初始化容器
     */
    static {
        strategyMap.put(PromotionKey.CASHBACK, new CashbackStrategy());
        strategyMap.put(PromotionKey.COUPON, new CouponStrategy());
        strategyMap.put(PromotionKey.GROUPBUY, new GroupBuyStrategy());
    }

    /**
     * 私有化构造函数
     */
    private PromotionStrategyFactory() {
    }

    /**
     * 获取策略实例对象
     *
     * @param strategyKey 策略key
     * @return 策略实例对象
     */
    public static IPromotionStrategy getPromotionStrategy(String strategyKey) {
        if (strategyKey == null) {
            return DEFAULT;
        }
        IPromotionStrategy strategy = strategyMap.get(strategyKey);
        // 策略不存在就使用默认策略
        return strategy == null ? DEFAULT : strategy;
    }

    /**
     * 默认策略
     */
    private static final IPromotionStrategy DEFAULT = new DefaultStrategy();

    /**
     * 其他策略的key
     */
    private interface PromotionKey {
        String CASHBACK = "CASHBACK";
        String COUPON   = "COUPON";
        String GROUPBUY = "GROUPBUY";
    }

}
